package com.hcss.common.util.excel.util;

import java.io.File;
import java.io.InputStream;

import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: Workbook 工具类
 * @Author:momo
 * @Since:2018年12月21日
 * @Version:1.1.0
 */
@Slf4j
public class WorkbookUtil {
	
	/**
	 * 是否需要加密
	 */
	private static final ThreadLocal<Boolean> needEncrypt = new ThreadLocal<Boolean>(){
		 @Override
		 protected Boolean initialValue() {
			 return false;
		 }
	};
	
	/**
	 * 是否已经加密
	 */
	private static final ThreadLocal<Boolean> isEncrypt = new ThreadLocal<Boolean>(){
		@Override
		 protected Boolean initialValue() {
			 return false;
		 }
	};
	
	/**
	 * 以不加密的方式创建新的工作簿
	 * @param isXlsx 是否为xlsx格式的Excel
	 */
	public static Workbook createBook(boolean isXlsx) {
		return createBook(isXlsx,null);
	}
	
	/**
	 * 创建新的工作簿
	 * @param isXlsx 判断Excel的版本 
	 * @param password 如果没有加密则传入null即可
	 * @return
	 */
	public static Workbook createBook(boolean isXlsx,String password) {
		Workbook workbook;
		if (isXlsx) {
			workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
			if(password != null && !"".equals(password)) {
				needEncrypt.set(true); // 07 加密不在这里
			}
		} else {
			workbook = new org.apache.poi.hssf.usermodel.HSSFWorkbook();
			if(password != null && !"".equals(password)) { // 03 方式进行加密
				needEncrypt.set(true);
				HSSFWorkbook wk = (HSSFWorkbook) workbook;
				Biff8EncryptionKey.setCurrentUserPassword(password); 
				wk.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), ""); 
				wk.unwriteProtectWorkbook();
				isEncrypt.set(true);
			}
		}
		return workbook;
	}
	
	/**
	 * 加载工作簿，只读模式
	 * 
	 * @param excelFile Excel文件
	 * @param password Excel工作簿密码，如果无密码传{@code null}
	 * @return {@link Workbook}
	 */
	public static Workbook createBook(File excelFile, String password) {
		try {
			return WorkbookFactory.create(excelFile, password);
		} catch (Exception e) {
			log.error("workboot create error!");
			return null;
		}
	}
	
	/**
	 * 以流的方式加载workbook
	 * @param is
	 * @param password
	 * @return
	 */
	public static Workbook createBook(InputStream is) {
		return createBook(is, null);
	}
	
	/**
	 * 以流的方式加载workbook
	 * @param is
	 * @param password
	 * @return
	 */
	public static Workbook createBook(InputStream is, String password) {
		try {
			return WorkbookFactory.create(is, password);
		} catch (Exception e) {
			log.error("workboot create error!");
			return null;
		}
	}
	
	
	
	// --------------- 设置与获取对应ThreadLocal的状态
	public static void setNeedEncrypt(Boolean flag) {
		needEncrypt.set(flag);
	}
	
	public static void setIsEncrypt(Boolean flag) {
		isEncrypt.set(flag);
	}
	
	public static Boolean getNeedEncrypt() {
		return needEncrypt.get();
	}
	
	public static Boolean getIsEncrypt() {
		return isEncrypt.get();
	}
	
}
